package com.studentstreet;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.Application;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Environment;

import com.studentstreet.component.LwtAlertDialog;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.Util;

public class MyApp extends Application {
	private List<Activity> activityList = new LinkedList<Activity>();
	private static MyApp instance;

	public MyApp() {
		super();
	}

	@Override
	public void onCreate() {
		super.onCreate();
		// 在SD卡上创建文件夹
		File f = new File(Environment.getExternalStorageDirectory()
				+ Util.APP_NAME + "/image/");
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	// 单例模式中获取唯一的MyApp 实例
	public static MyApp getInstance() {
		if (null == instance) {
			instance = new MyApp();
		}
		return instance;
	}

	// 添加Activity 到容器中
	public void addActivity(Activity activity) {
		activityList.add(activity);
	}

	// 遍历所有Activity 并finish
	public void exit(Activity activity) {
		Resources res = activity.getResources();
		LwtAlertDialog.Builder builder = new LwtAlertDialog.Builder(activity);
		builder.setTitle(res.getString(R.string.tips))
				.setMessage(res.getString(R.string.exit))
				.setPositiveButton(res.getString(R.string.sure),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								for (int i = 0; i < activityList.size(); i++) {
									activityList.get(i).finish();
								}
								// 保存登录信息
								PreferenceTools prefTools = new PreferenceTools(
										activityList.get(activityList.size() - 1));
								prefTools.saveIsLogin();
								System.exit(0);
							}
						})
				.setNegativeButton(res.getString(R.string.cancel), null).show();
	}

}
